import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置请求和响应解析方式
        req.setCharacterEncoding("utf-8");
        //2.获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") ||
        password == null || password.equals("")) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码为空，登录失败");
            return;
        }

        //从数据库中查询用户信息，并校验用户密码
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null || !password.equals(user.getPassword())) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //到了这里说明正确，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        //重定向到主页
        resp.sendRedirect("blog_list.html");
    }
}
